﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Quartz;
using Syspetro.Core;
using System;

namespace Syspetro.ServiceCore
{
    public static class QuartzConfigExtensions
    {
        public static void AddJobAndTrigger<T>(this IServiceCollectionQuartzConfigurator quartz) where T : IJob
        {
            string jobName = typeof(T).Name;
            var configKey = $"Quartz:{jobName}";
            var cronSchedule = InternalApp.Configuration[configKey];
            if (string.IsNullOrEmpty(cronSchedule))
            {
                throw new Exception($"No Quartz.NET Cron schedule found for job in configuration at {configKey}");
            }
            var jobKey = new JobKey(jobName);
            quartz.AddJob<T>(opts => opts.WithIdentity(jobKey));

            quartz.AddTrigger(opts => opts
                .ForJob(jobKey)
                .WithIdentity(jobName + "-trigger")
                .WithCronSchedule(cronSchedule));
        }
        public static IHostBuilder JobConfigureDelegate<J>(this IHostBuilder host) where J : IQuartzJobExtensions, new()
        {
            IQuartzJobExtensions QuartzJob = new J();

            InternalApp.ServiceCollection.AddQuartz(q =>
            {
                q.UseMicrosoftDependencyInjectionScopedJobFactory();
                QuartzJob.AddJobExtend(q);
            });
            InternalApp.ServiceCollection.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
            return host;
        }
    }
}
